package cn.com.pc.content.jpa;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Properties;

/**
 *  自定义的主键生成策略
 *
 *  如果填写了主键id，如果数据库中没有这条记录，则新增指定id的记录；否则更新记录
 *
 *  如果不填写主键id，则利用TableGenerator的自增策略指定id
 *
 */
public class TagManulGenerator extends TableGenerator {

    @Override
    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        params.put("prefer_entity_table_as_segment_value", true);
        params.put("target_table", "tags");
        params.put("initial_value", 3000);
        super.configure(type, params, serviceRegistry);
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor s, Object obj) throws HibernateException {
        Serializable id = s.getEntityPersister(null, obj).getClassMetadata().getIdentifier(obj, s);
        if (id != null && Long.parseLong(id.toString()) > 0) {
            return id;
        } else {
            return super.generate(s, obj);
        }
    }

}
